<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
    <script>
        let socket = null;

        function connect() {
            if (typeof(WebSocket) == "undefined") {
                console.log("您的浏览器不支持WebSocket");
            } else {
                console.log("您的浏览器支持WebSocket");

                // 实现化WebSocket对象，指定要连接的服务器地址与端口建立连接
                socket = new WebSocket($("#url").val());

                // 打开事件
                socket.onopen = function() {
                    console.log("Socket 已打开");

                    $("#status").html("已连接...");
                    //socket.send("这是来自客户端的消息" + location.href + new Date());
                };

                // 获得消息事件
                socket.onmessage = function(msg) {
                    console.log(msg.data);

                    // 发现消息进入，开始处理前端触发逻辑
                    $("#displayMsg").html($("#displayMsg").html() + "<br>" + msg.data);
                };

                // 关闭事件
                socket.onclose = function() {
                    console.log("Socket已关闭");

                    $("#status").html("未连接...");

                    socket = null;
                };

                // 发生了错误事件
                socket.onerror = function() {
                    alert("Socket发生了错误");
                }
            }
        }

        function send() {
            if(socket == null){
                alert("未连接");

                return false;
            }

            socket.send($("#sendMsg").val());
        }

        function closeConnect(){
            $("#status").html("已断开...");

            socket.close();
        }
    </script>
</head>
<body>
    连接地址:<input type="text" id="url" style="width:400px;" value="ws://127.0.0.1:8080/ws/webSocket/abc" />
    <button type="button" id="connect" onclick="connect()">连接</button>
    <button type="button" id="closeConnect" onclick="closeConnect()">断开</button>
    &nbsp;&nbsp;&nbsp;&nbsp;<div id="status" style="display:inline;">未连接...</div>
    <br><br>
    发送消息:<input type="text" id="sendMsg" style="width:400px;" />
    <button type="button"  onclick="send()">发送</button><br><br>
    <div>接收到消息:</div>
    <div id="displayMsg"></div>
</body>
</html>